from django_filters import rest_framework as filters
from tasks.models import TaskDefinition, Tasks
from django_celery_results.models import TaskResult
from django.db.models import Q

class TaskDefinitionFilter(filters.FilterSet):
    task_type = filters.CharFilter(method='filter_task_type', required=False)
    name = filters.CharFilter(field_name='name', lookup_expr='exact',required=False)
    
    def filter_task_type(self, queryset, name, value):
        """支持多个task_type查询，使用逗号分隔"""
        if not value:
            return queryset
        # 支持逗号分隔的多个类型
        types = [t.strip() for t in value.split(',') if t.strip()]
        if types:
            return queryset.filter(task_type__in=types)
        return queryset

    class Meta:
        model = TaskDefinition
        fields = ['task_type', 'name', 'creator', 'updater', 'create_time', 'update_time']


class TaskResultFilter(filters.FilterSet):
    # taskResult中的tasks_name就是PeriodicTask、Tasks中的task_func
    task_name = filters.CharFilter(field_name='task_name', lookup_expr='icontains', required=False)
    status = filters.CharFilter(field_name='status', lookup_expr='exact', required=False)
    periodic_task_name = filters.CharFilter(field_name='periodic_task_name', lookup_expr='icontains', required=False)
    date_created = filters.DateTimeFromToRangeFilter(field_name='date_created')
    date_done = filters.DateTimeFromToRangeFilter(field_name='date_done')
    
    class Meta:
        model = TaskResult
        fields = ['task_name', 'status', 'periodic_task_name', 'date_created', 'date_done', 'status']

    